<?php
namespace heihei\libs\weixin;

use Exception;
use heihei\helpers\HttpClientHelper;
use yii\base\BaseObject;
use Yii;

/**
 * 微信操作类
 */
class MP extends BaseObject {
    private $_cache = null;

    private $_appid = null;

    private $_secret = null;

    private $_accessToken = null;

    public function __construct($config = [])
    {
        parent::__construct($config);
        if(!$this->_accessToken && !$this->_appid && !$this->_secret){
            throw new Exception("accessToken与appid、secret必须有一组!");
        }
    }

    public function getCache(){
        if(!$this->_cache){
            $this->_cache = Yii::$app->dbCache;
        }
        return $this->_cache;
    }

    public function setCache($value){
        $this->_cache = $value;
    }

    public function getAppid(){
        return $this->_appid;
    }

    public function setAppid($value){
        $this->_appid = $value;
    }

    public function getSecret(){
        return $this->_secret;
    }

    public function setSecret($value){
        $this->_secret = $value;
    }

    public function getAccessToken($grantType = 'client_credential'){
        if($this->_accessToken){
            return $this->_accessToken;
        }

        if(!$this->_appid || !$this->_secret){
            throw new Exception("appid、secret属性不能为空！");
        }

        //读取缓存的数据
        $cacheKey = 'weixin.access_token.' . md5($this->_appid . '|' . $this->_secret);
        if($accessToken = $this->cache->get($cacheKey)){
            return $this->_accessToken = $accessToken;
        }

        $url = 'https://api.weixin.qq.com/cgi-bin/token?';
        $url = $url . 'grant_type=' . $grantType . '&appid=' . $this->_appid .'&secret=' . $this->_secret;
        $result = HttpClientHelper::getJson($url);
        if(isset($result['errcode']) && $result['errcode'] > 0){
            throw new Exception('获取access_token失败:' . $result['errmsg']);
        }
        if(!($accessToken = $result['access_token'])){
            throw new Exception('获取access_token失败未知错误！');
        }

        $this->cache->set($cacheKey, $accessToken, $result['expires_in'] - 360);
        return $this->_accessToken = $accessToken;
    }

    public function setAccessToken($value){
        $this->_accessToken = $value;
    }

    public function get($className, $config = []){
        $class = 'heihei\\libs\\weixin\\mp\\' . ucfirst($className);
        if(!class_exists($class)){
            throw new Exception("找不到类:" . $class);            
        }

        $config['api'] = $this;
        return new $class($config);
    }
}